
package com.feib.soeasy.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.WebAtmLog;
import com.feib.soeasy.model.WriteOffPayment;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.WebAtmLogService;
import com.feib.soeasy.util.CodeTableUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.integration.spring.SpringBean;


/**
 * @title (#)Soez9999ActionBean.java<br>
 * @description 線上繳款WEBATM 轉帳成功回饋處理<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/3/26 create by Jimmy Liu<br>
 */
public class Soez9999ActionBean extends BaseActionBean {
    
    private static final String DEFAULT_JSP = "/WEB-INF/views/soez9999/soez9999.jsp";
    
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
//    /**
//     * 交易日期 </br>
//     * ex:100-03-21 10:11:26
//     */
//    private String sysDateTime;
//    
//    /**
//     * 繳費名稱或代號</br>
//     */
//    private String channelType;
//    
//    /**
//     * 銷帳編號/繳款號碼</br>
//     */
//    private String cancelNo;
//    
//    /**
//     * 轉出帳號</br>
//     * ex:805-0000100400309371
//     */
//    private String trnAcct;
//    
//    /**
//     * 金額</br>
//     */
//    private String txAmt;
//    
//    /**
//     * 手續貰</br>
//     */
//    private String handleCharge;
//    
//    /**
//     * 交易序號</br>
//     * ex:62006
//     */
//    private String winnerNum;
    
    private WebAtmLog webAtmLog;
    
    @SpringBean("paymentService")
    private PaymentService paymentService;

    @SpringBean("webAtmLogService")
    private WebAtmLogService webAtmLogService;
    
    @DefaultHandler
    public Resolution doDefault() {
        logger.debug("Enter doDefault mehtod.");
        try {
            if (! validateIp())
            {
                webAtmLog.setLogNote("異常。非法來源IP: +" + this.getContext().getRequest().getRemoteAddr());
                return null;
            }
            WriteOffPayment writeOffPayment = new WriteOffPayment();
            writeOffPayment.setRlFlag(Boolean.TRUE); // 線上繳款
            writeOffPayment.setChannel(WriteOffPayment.CHANNEL_INTERNET_ATM); //通路-網路銀行
            writeOffPayment.setWriteOffStatus(WriteOffPayment.WRITEOFF_STATUS_OK);
            // 民國年
            String sysDateTime = webAtmLog.getSysDateTime();
            String chiYear = sysDateTime.substring(0, sysDateTime.indexOf("-"));
            // 銷帳日期, 轉日期格式
            writeOffPayment.setWriteOffDate(dateFormat.parse(String.valueOf((Integer.parseInt(chiYear,10) + 1911)) + sysDateTime.substring(sysDateTime.indexOf("-"))));
            // 實際繳費日
            writeOffPayment.setTxDate(writeOffPayment.getWriteOffDate());
            // 金額
            writeOffPayment.setAmount(new Double(webAtmLog.getTxAmt()).longValue());
            //黃郁珊 依中租需求修改
            int group_type = paymentService
					.getPaymentByGroup_type(this.webAtmLog.getCancelNo());
			//20111026 USERNO的銷帳編號，於PAYMENT主檔中所屬的公司GROUP_TYPE==4不即時銷帳
			if (group_type <= 0) {
				Payment payment = paymentService.getPaymentByVirtualAccount(
						this.webAtmLog.getCancelNo(), true); // 先找狀態為待繳款
				if (null != payment) {
					// 設定關聯
					writeOffPayment.setPayment(payment);
					paymentService.doWriteOffPaymentsOnLine(writeOffPayment);
					webAtmLog.setProcessStatus(new Integer(1)); // 正常銷帳
					webAtmLog.setLogNote("正常。PAYMENT.PAYMENT_PK="
							+ payment.getPaymentPk());
					logger.debug("線上繳款處理完畢");
				} else {
					// 此繳款編號沒有狀態為待繳款
					logger.debug("線上繳款:查無繳費單紀錄或已繳款");
					webAtmLog.setLogNote("異常。查無繳費單紀錄或已繳款");
				}
			} else {
				logger.debug("GROUP_TYPE==4不即時銷帳"+this.webAtmLog.getCancelNo());
			}
			
		} catch (Exception e) {
			String m = e.getMessage();
			if (m.length() > 20)
				m = m.substring(0, 20) + "...";
			webAtmLog.setLogNote("異常。系統錯誤," + m);
			logger.error("線上繳款發生錯誤：", e);
		} finally {
			// 寫LOG
			try {
				webAtmLogService.addWebAtmLog(webAtmLog);
			} catch (Exception e2) {
			}
		}
		return new ForwardResolution(DEFAULT_JSP);
	}
    
    protected boolean validateIp()
    {
        String remoteaddr = this.getContext().getRequest().getRemoteAddr();
        
        Map<String, String> ips = CodeTableUtil.getInstance().populateCodes("WEBATMIP");
                
        return null != ips.get(remoteaddr);
    }
    
    /* (non-Javadoc)
     * @see com.feib.soeasy.action.BaseActionBean#preBind()
     */
    @Override
    protected void preBind() {
        String sysDateTime = getContext().getRequest().getParameter("SysDateTime");
        String channelType = getContext().getRequest().getParameter("ChannelType");
        String cancelNo = getContext().getRequest().getParameter("CancelNo");
        String trnAcct = getContext().getRequest().getParameter("TrnAcct");
        String txAmt = getContext().getRequest().getParameter("TrnAmt");
        if (null != txAmt)
        	txAmt = txAmt.replaceAll("\\,", "").replaceAll("\\$", "");;
        String handleCharge = getContext().getRequest().getParameter("HandleCharge");
        if (null != handleCharge)
        	handleCharge = handleCharge.replaceAll("\\,", "").replaceAll("\\$", "");;
        String winnerNum = getContext().getRequest().getParameter("WinnerNum");
        
        webAtmLog = new WebAtmLog();
        webAtmLog.setCancelNo(cancelNo);
        webAtmLog.setChannelType(channelType);
        webAtmLog.setCreatedDate(new Date());
        webAtmLog.setHandleCharge(handleCharge);
        webAtmLog.setSysDateTime(sysDateTime);
        webAtmLog.setTrnAcct(trnAcct);
        webAtmLog.setTxAmt(txAmt);
        webAtmLog.setWinnerNum(winnerNum);
        webAtmLog.setProcessStatus(new Integer(2)); // default 異常
        super.preBind();
    }

    
    /**
     * @return the webAtmLog
     */
    public WebAtmLog getWebAtmLog() {
        return webAtmLog;
    }



}
